using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Tilemaps;

namespace ns
{
    ///<summary>
    ///
    ///</summary>
    public class Water : MonoBehaviour
    {
        public TileBase ground;
        public TileBase fire;
        public Tilemap tilemap;
        public TileBase rwater;
        public TileBase lwater;
        Vector3Int currentPosition;
        public Animator animator;
        public UIMainWindow mainWindow;
        public TileBase tile;
        int count;
        public GameObject smoke;
        public IEnumerator PullWater()
        {
            while(true)
            {
                tile = tilemap.GetTile(currentPosition);
                if (tile == fire)
                {
                    Fire();
                    break;
                }
                if (tile == ground )
                {
                    Ground();
                    break;
                }
                yield return new WaitForSeconds(0.25f);
                currentPosition.y -= 1;
            }
            
        }

        private void Fire()
        {
            tilemap.SetTile(currentPosition, null);
            GameObject.Instantiate(smoke, tilemap.CellToWorld(currentPosition), Quaternion.identity);
        }

        private void Ground()
        {
            for (int i = -1; i <3 ; i++) 
            {
                if (tilemap.GetTile(currentPosition + new Vector3Int(i, 0, 0)) != null)
                {
                    if ((i + 1) % 2 != 0)
                    {
                        tilemap.SetTile(currentPosition + new Vector3Int(i, 0, 0), rwater);
                    }
                    else
                    {
                        tilemap.SetTile(currentPosition + new Vector3Int(i, 0, 0), lwater);
                    }
                }
            }
        }

        private void Start()
        {
            tilemap = GameObject.Find("Tilemap").GetComponent<Tilemap>();
            count = 0;
            mainWindow =FindObjectOfType<UIMainWindow>();
            animator= GetComponent<Animator>();
            currentPosition = tilemap.WorldToCell(gameObject.transform.position);
        }
        public void Update()
        {
            if (mainWindow.fsm.isgo) 
            {
                if (count==0)
                {
                    animator.SetBool("pull", true);
                    StartCoroutine(PullWater());
                    count++;
                }
            }
        }
        public void End()
        {
            StopCoroutine(PullWater());
            Destroy(gameObject);
        }
    }
}
